package com.tb.controller;

import com.qiniu.common.QiniuException;
import com.tb.pojo.User;
import com.tb.utils.Msg;
import com.tb.utils.QiniuUploadImageUtil;
import com.tb.utils.Utf8;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;

/**
 * 图片上传接口
 * @author 何龙
 * @create 2019-01-09 20:20
 */
@RestController
@RequestMapping("/img")
public class UploadPictureController {
    @GetMapping("/upload")
    public Msg upload(@RequestParam(value = "imgPath",defaultValue = "")String imgPath){
        if ("".equals(imgPath)){
            return Msg.error( 1,"缺少参数:imgPath" );
        }
        int i = QiniuUploadImageUtil.imgType( Utf8.getString( imgPath ) );
        if (i==1){
            return Msg.error( 1,"文件格式不正确，只能上传图片！" );
        }else if (i==2){
            return Msg.error( 1,"文件路径不正确！" );
        }else {
            try {
                String s = QiniuUploadImageUtil.fileUpload( Utf8.getString( imgPath ) );
                return Msg.success(s);
            } catch (QiniuException e) {
                return Msg.error( 1,"上传失败！" );
            }
        }
    }

    /**
     * @api {POST} /img/uploadImage 图片上传接口
     * @apiDescription 图片上传&nbsp;&nbsp;<span style="color:#D0254E">[*需要在管理员登录状态下请求]</span>
     *  <br/><span style="color:#012456"><b>作者:何龙</b></span>
     * @apiGroup Img APIs
     *
     *
     * @apiParam {file} file 用input上传的图片&nbsp;&nbsp;<span style="color:#D0254E">[*必选字段]</span>
     *
     * @apiVersion 1.0.0
     *
     * @apiSuccess  {int} code 返回状态码
     *                    <br/>0:正常<br/>1:文件格式错误或路径非法<br/>999:未登录或登陆超时
     * @apiSuccess  {string} msg 返回错误信息
     * @apiSuccess  {Object} data 上传的图片外链
     *
     *
     * @apiParamExample {json} 异步上传图片的html样例:
     *
     * <body>
     * <form id="ff" enctype="multipart/form-data" method="post">
     *     <input id="file" type="file" name="file"  multiple="multiple"/><br/>
     *     <input type="button" value="插件异步上传" onclick="upload()"/>
     * </form>
     *
     * <script type="text/javascript" src="http://code.jquery.com/jquery-2.0.1.min.js"></script>
     * <script type="text/javascript" src="https://cdn.bootcss.com/jquery.form/4.2.2/jquery.form.min.js"></script>
     *
     * <script>
     *     function upload(){
     *         if($('#file').val() === ""){
     *             alert('你没有选中文件!');
     *             return ;
     *         }
     *         var options = {
     *             type: "post",
     *             url : "img/uploadImage",
     *             dataType: "text",
     *             success : function(data) {
     *                 //返回data为json字符串，转化为json对象
     *                 var obj = eval('('+ data +')');
     *                 //判断状态
     *                 if (obj.code === 0) {//状态为成功
     *                     //obj.data为返回图片外链
     *                     $("#ff").append('<img width="400" src="'+obj.data+'"/>');
     *                 }else{//上传失败 obj.msg为失败信息
     *                     alert(obj.msg);
     *                 }
     *             }
     *         };
     *         //jquery-form用插件异步提交
     *         $('#ff').ajaxSubmit(options);
     *     }
     * </script>
     *
     * </body>
     *
     *
     * @apiSuccessExample {json} 正确返回值:
     *     {
     *     "code": 0,
     *     "msg": "",
     *     "data": "http://pky36u4fr.bkt.clouddn.com/Flfd05ApAiqlYCMI6SgZQTK8Ab7q"
     *     }
     *
     * @apiErrorExample {json} 错误返回值:
     *     {
     *     "code": 999,
     *     "msg": "登陆超时!",
     *     "data": null
     *     }
     *
     * @apiSampleRequest  /img/uploadImage
     */
    @PostMapping("/uploadImage")
    public Msg upload(
            @RequestParam(value = "file",required = false) CommonsMultipartFile file,
            HttpSession session){
        try {
            String path = session.getServletContext().getRealPath("/")+file.getOriginalFilename();
            int i = QiniuUploadImageUtil.imgType( Utf8.getString( path ) );
            if (i==1){
                return Msg.error( 1,"文件格式不正确，只能上传图片！" );
            }else if (i==2){
                return Msg.error( 1,"文件路径不正确！" );
            }
            file.transferTo(new File(path));
            String url =QiniuUploadImageUtil.fileUpload(path);
            File f = new File(path);
            f.delete();
            return Msg.success( url );
        }catch (Exception e){
            return Msg.error(1,"上传失败！");
        }
    }
}
